Imports System.Data.SqlClient
Imports System.Drawing
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraGrid.Columns
Imports DevExpress.XtraEditors
Imports DevExpress.XtraScheduler
Imports DevExpress.XtraScheduler.UI
Imports DevExpress.XtraEditors.Repository

'--- Created Date On : 16-Nov-2010 (Jagdish)

Public Class frmItemDetails
    Dim mstrMode As String
    Public blnAdd As Boolean, blnEdit As Boolean, blnDelete As Boolean, blnLocked As Boolean
    Dim mlngRecordID As Long
    Dim blnUnload As Boolean
    Dim mblnChanged As Boolean
    Dim mblnActivate As Boolean
    Dim mblnExpanded As Boolean = False
    Dim mblnAutoSize As Boolean = True
    Dim gridView1 As Views.Grid.GridView
    Dim mblnCancelDisplay As Boolean
    Public mblnFrmOutside As Boolean = False
    Public mstrItemName As String
    Public mstrMenuList(20)() As String    'Keeps menu details (Jagged Arrays)

    Private Sub initializeMenu()
        Try
            'Middle -1 Group
            'Middle -2 Locked

            'Last -1 Checked

            mstrMenuList(0) = New String() {"Main", 1, 0, "Main"}

            mstrMenuList(1) = New String() {"Item Code", 2, 1, "A.ItemCode"}
            mstrMenuList(2) = New String() {"Item Name", 2, 1, "A.ItemName"}
            mstrMenuList(3) = New String() {"Bar Code No", 2, 1, "A.BarCodeNo"}
            mstrMenuList(4) = New String() {"Category", 2, 1, "A.Category"}
            mstrMenuList(5) = New String() {"Manufacturer", 0, 1, "A.ManufacturerName"}
            mstrMenuList(6) = New String() {"Vendor", 0, 1, "A.VendorName"}
            mstrMenuList(7) = New String() {"Purchase Unit", 0, 1, "A.PurchaseUnit"}
            mstrMenuList(8) = New String() {"Purchase Unit Cost", 0, 1, "A.PurchaseUnitCost"}
            mstrMenuList(9) = New String() {"Dispensing Unit Per Purchase", 0, 1, "A.DispensingUnitQty"}
            mstrMenuList(10) = New String() {"Cost Each", 0, 1, "A.CostEach"}
            mstrMenuList(11) = New String() {"ReOrder Point", 0, 1, "A.ReOrderPoint"}
            mstrMenuList(12) = New String() {"ReOrder Qty", 0, 1, "A.ReOrderQty"}
            mstrMenuList(13) = New String() {"Opening Stock", 0, 1, "A.OpeningStock"}
            mstrMenuList(14) = New String() {"Preferred QOH", 0, 1, "A.PreferredQOH"}
            mstrMenuList(15) = New String() {"QOH", 0, 1, "A.QOH"}
            mstrMenuList(16) = New String() {"Shelf Life", 0, 1, "A.ShelfLifePeriod"}
            mstrMenuList(17) = New String() {"Billable", 0, 1, "A.IsBillable"}
            mstrMenuList(18) = New String() {"Dispensing Unit", 0, 1, "A.DispensingUnit"}
            mstrMenuList(19) = New String() {"Charge To Patient", 0, 1, "A.ChargeToPatient"}

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub chkBillable_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkBillable.CheckedChanged
        If chkBillable.Checked = True Then
            lkDispensingUnit.Enabled = True
            txtCharge.Enabled = True
        ElseIf chkBillable.Checked = False Then
            lkDispensingUnit.EditValue = Nothing
            txtCharge.EditValue = 0.0
            lkDispensingUnit.Enabled = False
            txtCharge.Enabled = False
        End If
    End Sub

    Private Sub frmItemDetails_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
        Try
            If mblnActivate = True Then
                mblnActivate = False

                pbRecords.Visible = True
                pbRecords.BringToFront()
                Application.DoEvents()
                pbRecords.Position = 20

                'Fill Category combo
                Call PopulateLookupDX(lkCategory, "Category", "CategoryId", "tblCategory", "CategoryId,Category", "IsFixed=0", "Category")
                'Fill Manufacturer combo
                Call PopulateLookupDX(lkManufacturer, "ManufacturerName", "ManufacturerId", "vwManufacturerDetails", "ManufacturerId,ManufacturerName", , "ManufacturerName")
                'Fill Vendor combo
                Call PopulateLookupDX(lkVendor, "VendorName", "VendorId", "vwVendorDetails", "VendorId,VendorName", , "VendorName")
                'Fill Purchase Unit
                Call PopulateLookupDX(lkPurchaseUnit, "Units", "UnitId", "tblInventoryUnits", "UnitId,Units", , "Units")
                'Fill Dispensing Unit
                Call PopulateLookupDX(lkDispensingUnit, "Units", "UnitId", "tblInventoryUnits", "UnitId,Units", , "Units")

                Call PopulateData()
                pbRecords.Position = 100
                pbRecords.Visible = False
                grdRecords.Focus()
                If mblnFrmOutside = True Then
                    btnAdd_Click(Nothing, Nothing)
                    If mstrItemName = "" Then
                        txtItemName.Text = ""
                        txtItemName.Focus()
                    Else
                        txtItemName.Text = mstrItemName
                        lkCategory.Focus()
                    End If
                End If
            End If

        Catch ex As Exception
            pbRecords.Visible = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub frmItemDetails_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Try

            Dim intUnload As DialogResult

            If mblnChanged = True And mstrMode <> "" Then
                intUnload = MessageBox.Show("You have not saved your changes to the record. Do you want to save your changes now?", gstrMessage, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
                If intUnload = Windows.Forms.DialogResult.Cancel Then
                    e.Cancel = True : Exit Sub
                ElseIf intUnload = Windows.Forms.DialogResult.Yes Then
                    blnUnload = True
                    If blnSaveRecords() = False Then
                        e.Cancel = True
                        blnUnload = False
                        Exit Sub
                    End If
                    mblnChanged = False
                End If
            End If
            blnUnload = False

        Catch ex As Exception
            blnUnload = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub frmItemDetails_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        mblnCancelDisplay = True
        If blnKeyTrap(e.KeyCode, Me, True, grdRecords) = True Then mblnCancelDisplay = False : Exit Sub
        mblnCancelDisplay = False

        If e.KeyCode = Keys.F5 Then
            gdvRecords_FocusedRowChanged(Nothing, Nothing)
        End If

        pbRecords.Visible = False
    End Sub

    Private Sub frmItemDetails_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try

            Call SetImageControl(Me)
            Me.Icon = System.Drawing.Icon.FromHandle(CType(mdiMain.imgFormIcons.Images(2), Bitmap).GetHicon())
            Call btnExpand_Click(Me, e)
            Call GetAccessPermission(Me, "frmItemDetails")
            Call initializeMenu()
            Call setPBRecords(Me, pbRecords)
            mblnActivate = True
            mblnChanged = False

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub
    Public Sub PopulateData()
        Dim dsRecords As New DataSet   'For populating data in XtraGrid
        Dim strQuery As String = ""
        Dim strTemp As String = ""
        Dim intCtr As Int16

        Try
            pbRecords.Position = 40 : Application.DoEvents()

            For intCtr = 0 To mstrMenuList.GetUpperBound(0) - 1
                If mstrMenuList(intCtr)(1) <> 1 And mstrMenuList(intCtr)(2) <> 0 Then
                    strTemp = mstrMenuList(intCtr)(3)
                    strQuery = strQuery & "," & strTemp & " [" & mstrMenuList(intCtr)(0) & "]"
                End If
            Next

            strQuery = "select A.ItemId [record_id]" & strQuery & " From vwItemDetails A " & _
                        "Order By ItemId"

            dsRecords = FillDataSet(strQuery)
            'Bind the grid control to the data source
            gdvRecords.Columns.Clear()

            With grdRecords
                .BeginUpdate()
                .DataSource = dsRecords.Tables(0)
                .EndUpdate()
                .ForceInitialize()
            End With

            With gdvRecords
                'Primary Key Field
                .Columns("record_id").Visible = False
                .Columns("record_id").OptionsColumn.ShowInCustomizationForm = False
                .ExpandAllGroups()
                .BestFitColumns()
            End With

            dsRecords.Dispose()
            pbRecords.Position = 80 : Application.DoEvents()

            'To set row count
            Call gdvRecords_ColumnFilterChanged(Nothing, Nothing)

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub btnExpand_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExpand.Click
        If mblnExpanded = True Then
            mblnExpanded = False
            btnExpand.Image = mdiMain.imgEditIcons.Images(0)
            grdRecords.Width = 190
            Call btnCancel_Click(Nothing, Nothing)
        Else
            mblnExpanded = True
            btnExpand.Image = mdiMain.imgEditIcons.Images(1)
            grdRecords.Width = 772 : grdRecords.BringToFront()
            If gdvRecords.RowCount > 0 Then mlngRecordID = lngGetSelectID(gdvRecords, "record_id")
        End If

        gdvRecords.OptionsView.ColumnAutoWidth = False
        grdRecords.Focus()
    End Sub

    Private Sub DisplayData()
        'Display data in form fields.
        Dim dsTemp As DataSet
        Try

            dsTemp = FillDataSet("select * from tblItem where ItemId=" & mlngRecordID)

            With dsTemp.Tables(0)
                If .Rows.Count > 0 Then
                    txtItemCode.Text = Trim(.Rows(0).Item("ItemCode") & "")
                    txtBarCodeNo.Text = Trim(.Rows(0).Item("BarCodeNo") & "")
                    txtItemName.Text = Trim(.Rows(0).Item("ItemName") & "")
                    lkCategory.EditValue = CInt(Val(.Rows(0).Item("CategoryId")))
                    lkManufacturer.EditValue = CInt(Val(.Rows(0).Item("ManufacturerId")))
                    txtDetails.Text = Trim(.Rows(0).Item("Details") & "")
                    lkVendor.EditValue = CInt(Val(.Rows(0).Item("VendorId")))
                    lkPurchaseUnit.EditValue = CInt(.Rows(0).Item("PurchaseUnitId"))
                    txtPurchaseUnitCost.EditValue = Val(.Rows(0).Item("PurchaseUnitCost"))
                    txtDispensingUnit.Text = Val(.Rows(0).Item("DispensingUnit"))
                    txtCostEach.EditValue = Val(.Rows(0).Item("CostEach"))
                    txtReOrderPoint.Text = Val(.Rows(0).Item("ReOrderPoint"))
                    txtReOrderQty.Text = Val(.Rows(0).Item("ReOrderQty"))
                    txtPreferredQOH.Text = Val(.Rows(0).Item("PreferredQOH"))
                    txtShelfLife.Text = Val(.Rows(0).Item("ShelfLife"))
                    cboShelfPeriod.Text = Trim(.Rows(0).Item("ShelfPeriod") & "")
                    chkBillable.Checked = .Rows(0).Item("IsBillable")
                    If IsDBNullOrNothing(.Rows(0).Item("DispensingUnitId")) Then
                        lkDispensingUnit.EditValue = Nothing
                    Else
                        lkDispensingUnit.EditValue = CInt(.Rows(0).Item("DispensingUnitId"))
                    End If
                    txtOpeningStock.EditValue = Val(.Rows(0).Item("OpeningStock"))
                    txtQOH.Text = Val(.Rows(0).Item("QOH"))
                    txtCharge.EditValue = Val(.Rows(0).Item("ChargeToPatient"))
                    If Not IsDBNullOrNothing(.Rows(0).Item("ImagePath")) Then
                        pcbImage.Image = Nothing
                        pcbImage.Image = Image.FromFile(.Rows(0).Item("ImagePath"))
                        pcbImage.Tag = Trim(.Rows(0).Item("ImagePath") & "")
                    End If
                End If
            End With

            dsTemp.Dispose()

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Call EnableDisableControls(True)

        If mstrMode = "Add" Then
            If gdvRecords.RowCount > 0 Then
                mlngRecordID = lngGetSelectID(gdvRecords, "record_id")
                DisplayData()
            Else
                ClearControls()
                btnEdit.Enabled = False : btnDelete.Enabled = False
            End If
        Else
            If gdvRecords.RowCount = 0 Then
                ClearControls()
                btnEdit.Enabled = False : btnDelete.Enabled = False
            Else
                DisplayData()
            End If
        End If

        Me.Text = "Item Details"
        mstrMode = ""
        mblnChanged = False
    End Sub

    Private Sub EnableDisableControls(ByVal blnEnable As Boolean)
        If blnAdd = True Then btnAdd.Enabled = blnEnable
        If blnEdit = True Then btnEdit.Enabled = blnEnable
        If blnDelete = True Then btnDelete.Enabled = blnEnable

        btnSave.Enabled = Not (blnEnable) : btnCancel.Enabled = Not (blnEnable)

        grbControls.Enabled = Not (blnEnable)
    End Sub


    Private Sub gdvRecords_ColumnFilterChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvRecords.ColumnFilterChanged
        gdvRecords.Columns(1).SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Count, "Total {0} Record(s)")

        Dim lngTemp As Long = lngGetSelectID(gdvRecords, "record_id")
        If mlngRecordID <> lngTemp Or btnCancel.Enabled = True Then
            gdvRecords_FocusedRowChanged(Nothing, Nothing)
        End If
    End Sub

    Private Sub gdvRecords_CustomDrawRowIndicator(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs) Handles gdvRecords.CustomDrawRowIndicator
        SetRowIndicator(e)
    End Sub

    Private Sub gdvRecords_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvRecords.DoubleClick
        If btnEdit.Enabled = True Then
            Call btnEdit_Click(Nothing, Nothing)
        End If
    End Sub

    Private Sub gdvRecords_FocusedRowChanged(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles gdvRecords.FocusedRowChanged
        Try
            If mblnCancelDisplay = True Then Exit Sub

            mlngRecordID = lngGetSelectID(gdvRecords, "record_id")

            If gdvRecords.RowCount > 0 Then
                btnEdit.Enabled = blnEdit : btnDelete.Enabled = blnDelete

            Else
                ClearControls()
                btnEdit.Enabled = False : btnDelete.Enabled = False
            End If
            btnAdd.Enabled = blnAdd

            If mlngRecordID = 0 Then Exit Sub

            If mblnExpanded = True Then Exit Sub

            Call btnCancel_Click(Nothing, Nothing)

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub gdvRecords_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvRecords.GotFocus
        If btnCancel.Enabled = True And Me.Visible = True Then Call btnCancel_Click(Nothing, Nothing)
    End Sub

    Private Sub gdvRecords_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles gdvRecords.KeyDown
        Try

            If e.KeyCode = Keys.Delete And btnDelete.Enabled = True Then
                Call btnDelete_Click(Nothing, Nothing)
            ElseIf e.KeyCode = Keys.Return And btnDelete.Enabled = True Then
                Call gdvRecords_DoubleClick(Nothing, Nothing)
            ElseIf e.KeyCode = Keys.Escape Then
                Call btnClose_Click(Nothing, Nothing)
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub btnClose_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()
        GC.Collect()
    End Sub

    Private Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Dim strTemp As String
        Try
            If mblnExpanded = True Then btnExpand_Click(Nothing, Nothing)
            Call EnableDisableControls(False)
            Call ClearControls()
            mstrMode = "Add"
            mlngRecordID = 0
            Me.Text = "Item Details [Add]"
            strTemp = strRecordID("tblItem", "top 1 ItemCode", "ItemId>0 order by ItemId desc")
            txtItemCode.Text = IIf(strTemp = "Null", IncrementTextValue("I0000", 1), IncrementTextValue(strTemp, 1))
            mblnChanged = False
            txtItemCode.Focus()
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Function IsValidEntry() As Boolean
        'Here check valid entry of fields
        Dim strMsg As String = ""
        IsValidEntry = False

        If IsDBNullOrNothing(txtItemCode.Text) Then
            strMsg = "Please enter Item Code"
            txtItemCode.Focus()
        ElseIf IsDBNullOrNothing(txtItemName.Text) Then
            strMsg = "Please enter Item Name"
            txtItemName.Focus()
        ElseIf IsDBNullOrNothing(lkCategory.EditValue) Then
            strMsg = "Please select Category"
            lkCategory.Focus()
        ElseIf IsDBNullOrNothing(lkManufacturer.EditValue) Then
            strMsg = "Please select Manufacturer"
            lkManufacturer.Focus()
        ElseIf IsDBNullOrNothing(lkVendor.EditValue) Then
            strMsg = "Please select Vendor"
            lkVendor.Focus()
        ElseIf IsDBNullOrNothing(lkPurchaseUnit.EditValue) Then
            strMsg = "Please select Purchase Unit"
            lkPurchaseUnit.Focus()
        ElseIf IsDBNullOrNothing(txtPurchaseUnitCost.Text) Or Val(txtPurchaseUnitCost.EditValue) <= 0 Then
            strMsg = "Please enter Purchase Unit Cost"
            txtPurchaseUnitCost.Focus()
        ElseIf IsDBNullOrNothing(txtDispensingUnit.Text) Or Val(txtDispensingUnit.EditValue) <= 0 Then
            strMsg = "Please enter Dispensing Unit per Purchase"
            txtDispensingUnit.Focus()
        ElseIf chkBillable.Checked = True And IsDBNullOrNothing(lkDispensingUnit.EditValue) Then
            strMsg = "Please select Dispensing Unit"
            lkDispensingUnit.Focus()
        ElseIf chkBillable.Checked = True And Val(txtCharge.EditValue) <= 0 Then
            strMsg = "Please enter Charge to Patient"
            txtCharge.Focus()
        End If

        If Trim(strMsg) <> "" Then
            IsValidEntry = False
            MessageBox.Show(strMsg, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Else
            IsValidEntry = True
        End If
    End Function

    Private Function blnSaveRecords() As Boolean
        Dim blnIsTransactionOpen As Boolean
        Dim strQuery As String = ""
        Try
            blnSaveRecords = False

            If IsValidEntry() = False Then
                Exit Function
            End If

            strQuery = "ItemCode='" & Replace(Trim(txtItemCode.Text), "'", "''") & "'" & _
                        IIf(mstrMode = "Edit", " and ItemId<>" & mlngRecordID, "")
            If strRecordID("tblItem", "1", strQuery) <> "Null" Then
                MessageBox.Show("This Item Code already exists", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                txtItemCode.Focus()
                Exit Function
            End If

            If IsDBNullOrNothing(txtBarCodeNo.Text) = False Then
                strQuery = "BarCodeNo='" & Replace(Trim(txtBarCodeNo.Text), "'", "''") & "'" & _
                        IIf(mstrMode = "Edit", " and ItemId<>" & mlngRecordID, "")
                If strRecordID("tblItem", "1", strQuery) <> "Null" Then
                    MessageBox.Show("This BarCode No already exists", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    txtBarCodeNo.Focus()
                    Exit Function
                End If
            End If

            If (blnUnload = False) Then
                If (MessageBox.Show("Are you sure to " & IIf(mstrMode = "Add", "add", "modify") & " this item.", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = System.Windows.Forms.DialogResult.No) Then
                    txtItemCode.Focus()
                    Exit Function
                End If
            End If

            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True
            If (mstrMode = "Add") Then
                mlngRecordID = lngAutogeneratePrimaryKey("tblItem", "ItemId")
                strQuery = mlngRecordID & _
                            " , " & SmartReplace(txtItemCode.Text) & _
                            " , " & SmartReplace(txtBarCodeNo.Text) & _
                            " , " & SmartReplace(txtItemName.Text) & _
                            " , " & SmartReplace(lkCategory.EditValue) & _
                            " , " & SmartReplace(lkManufacturer.EditValue) & _
                            " , " & SmartReplace(txtDetails.Text) & _
                            " , " & SmartReplace(lkVendor.EditValue) & _
                            " , " & SmartReplace(lkPurchaseUnit.EditValue) & _
                            " , " & Val(txtPurchaseUnitCost.EditValue) & _
                            " , " & Val(txtDispensingUnit.EditValue) & _
                            " , " & Val(txtCostEach.EditValue) & _
                            " , " & Val(txtReOrderPoint.EditValue) & _
                            " , " & Val(txtReOrderQty.EditValue) & _
                            " , " & Val(txtPreferredQOH.EditValue) & _
                            " , " & Val(txtShelfLife.EditValue) & _
                            " , " & IIf(chkBillable.Checked = True, 1, 0) & _
                            " , " & SmartReplace(lkDispensingUnit.EditValue) & _
                            " , " & Val(txtCharge.EditValue) & _
                            " , " & SmartReplace(pcbImage.Tag) & _
                            " , " & Val(txtOpeningStock.EditValue) & _
                            " ,0, " & SmartReplace(gstrUserName & "-" & Format(gdtCurrentDate, "dd-MMM-yyyy hh:mm:ss tt")) & _
                            " , " & SmartReplace(cboShelfPeriod.Text)
                Call InsertintoTable("tblItem", strQuery)

                strQuery = lngAutogeneratePrimaryKey("tblInventoryStock", "StockId")
                strQuery = strQuery & "," & mlngRecordID & _
                            " , NULL,NULL,NULL" & _
                            " , '01-Jan-2010'" & _
                            " , " & mlngRecordID & _
                            " , " & Val(txtOpeningStock.EditValue) & _
                            " , 0"
                Call InsertintoTable("tblInventoryStock", strQuery)
            ElseIf (mstrMode = "Edit") Then
                strQuery = "ItemCode=" & SmartReplace(txtItemCode.Text) & _
                            " , BarCodeNo=" & SmartReplace(txtBarCodeNo.Text) & _
                            " , ItemName=" & SmartReplace(txtItemName.Text) & _
                            " , CategoryId=" & SmartReplace(lkCategory.EditValue) & _
                            " , ManufacturerId=" & SmartReplace(lkManufacturer.EditValue) & _
                            " , Details=" & SmartReplace(txtDetails.Text) & _
                            " , VendorId=" & SmartReplace(lkVendor.EditValue) & _
                            " , PurchaseUnitId=" & SmartReplace(lkPurchaseUnit.EditValue) & _
                            " , PurchaseUnitCost=" & Val(txtPurchaseUnitCost.EditValue) & _
                            " , DispensingUnit=" & Val(txtDispensingUnit.EditValue) & _
                            " , CostEach=" & Val(txtCostEach.EditValue) & _
                            " , ReOrderPoint=" & Val(txtReOrderPoint.EditValue) & _
                            " , ReOrderQty=" & Val(txtReOrderQty.EditValue) & _
                            " , PreferredQOH=" & Val(txtPreferredQOH.EditValue) & _
                            " , ShelfLife=" & Val(txtShelfLife.EditValue) & _
                            " , IsBillable=" & IIf(chkBillable.Checked = True, 1, 0) & _
                            " , DispensingUnitId=" & SmartReplace(lkDispensingUnit.EditValue) & _
                            " , ChargeToPatient=" & Val(txtCharge.EditValue) & _
                            " , ImagePath=" & SmartReplace(pcbImage.Tag) & _
                            " , OpeningStock=" & Val(txtOpeningStock.EditValue) & _
                            " , LastModified=" & SmartReplace(gstrUserName & "-" & Format(gdtCurrentDate, "dd-MMM-yyyy hh:mm:ss tt")) & _
                            " , ShelfPeriod=" & SmartReplace(cboShelfPeriod.Text)

                Call UpdateTable("tblItem", strQuery, "ItemId=" & mlngRecordID)

                Call UpdateTable("tblInventoryStock", "QtyIn=" & Val(txtOpeningStock.EditValue), "OpeningId=" & mlngRecordID & "")

            End If

            blnSaveRecords = True

            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False

        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            If ex.Message.Contains("Negative") Then
                MessageBox.Show("After this transaction Stock will be Negative.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Else
                MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
                AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                    Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
            End If
        End Try
    End Function

    Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Dim lngTemp As Long, lngRowID As Long
        Try
            If mblnChanged = False And mstrMode <> "Add" Then
                btnCancel_Click(Nothing, Nothing)
                Exit Sub
            End If

            If blnSaveRecords() = False Then Exit Sub
            
            lngTemp = mlngRecordID

            pbRecords.Visible = True
            pbRecords.BringToFront()
            Application.DoEvents()
            pbRecords.Position = 20

            gdvRecords.OptionsSelection.EnableAppearanceFocusedRow = False
            gdvRecords.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.None
            mblnCancelDisplay = True
            Call PopulateData()
            mblnCancelDisplay = False

            pbRecords.Position = 95
            If gdvRecords.RowCount > 0 Then
                lngRowID = LocateRowBySingleValue(grdRecords, lngTemp)
                gdvRecords.FocusedRowHandle = lngRowID
                If lngRowID = 0 Then gdvRecords_FocusedRowChanged(Nothing, Nothing)
            Else
                Call btnCancel_Click(Nothing, Nothing)
            End If
            gdvRecords.OptionsSelection.EnableAppearanceFocusedRow = True
            gdvRecords.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus

            pbRecords.Position = 100
            pbRecords.Visible = False

            If mblnFrmOutside = True Then
                mlngLookUpId = mlngRecordID
                Me.Close()
            End If
        Catch ex As Exception
            pbRecords.Visible = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub btnEdit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        Try

            If mblnExpanded = True Then btnExpand_Click(Nothing, Nothing)

            Call EnableDisableControls(False)
            mblnChanged = False
            mstrMode = "Edit"
            Me.Text = "Item Details [Edit]"
            'txtVendorName.Focus()
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub gdvRecords_ShowGridMenu(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Grid.GridMenuEventArgs) Handles gdvRecords.ShowGridMenu
        If e.MenuType = DevExpress.XtraGrid.Views.Grid.GridMenuType.Column Then
            Dim mainMenu As DevExpress.XtraGrid.Menu.ViewMenu = CType(e.Menu, DevExpress.XtraGrid.Menu.ViewMenu)
            Dim mainItem As New DevExpress.Utils.Menu.DXMenuItem("Column Auto Width", New EventHandler(AddressOf MainMenuItem))
            mainItem.BeginGroup = True
            mainItem.Tag = e.Menu
            mainMenu.Items.Add(mainItem)
            mainItem.Image = IIf(mblnAutoSize = True, mdiMain.imgEditIcons.Images(13), Nothing)
        End If
    End Sub

    Private Sub MainMenuItem(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim Item As DevExpress.Utils.Menu.DXMenuItem = CType(sender, DevExpress.Utils.Menu.DXMenuItem)
        Dim menu As DevExpress.XtraGrid.Menu.GridViewMenu = CType(Item.Tag, DevExpress.XtraGrid.Menu.GridViewMenu)
        mblnAutoSize = Not (mblnAutoSize)
        gdvRecords.OptionsView.ColumnAutoWidth = (mblnAutoSize = True)
        If gdvRecords.OptionsView.ColumnAutoWidth = False Then gdvRecords.BestFitColumns()
    End Sub


    Private Sub ClearControls()
        Try
            Call Clearfields(grbDispensingDetails)
            Call Clearfields(grbItemDetails)
            Call Clearfields(grbPurchase)
            Call Clearfields(grbStockManagement)
            txtPurchaseUnitCost.EditValue = 0.0
            txtDispensingUnit.EditValue = 0
            txtCostEach.EditValue = 0.0
            txtReOrderPoint.EditValue = 0
            txtReOrderQty.EditValue = 0
            txtPreferredQOH.EditValue = 0
            txtOpeningStock.EditValue = 0
            txtQOH.EditValue = 0
            txtShelfLife.EditValue = 0
            txtCharge.EditValue = 0.0
            cboShelfPeriod.SelectedIndex = 0
            pcbImage.Image = Nothing
            pcbImage.Tag = ""

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Public Sub SetRowFromOutside(ByVal RecID As Long)
        Dim lngRowID As Long
        gdvRecords.OptionsSelection.EnableAppearanceFocusedRow = False
        gdvRecords.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.None
        lngRowID = LocateRowBySingleValue(grdRecords, RecID)
        gdvRecords.FocusedRowHandle = lngRowID
        If lngRowID = 0 Then gdvRecords_FocusedRowChanged(Nothing, Nothing)
        gdvRecords.OptionsSelection.EnableAppearanceFocusedRow = True
        gdvRecords.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus
    End Sub

    Private Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim blnTrnasaction As Boolean

        Try

            If MessageBox.Show("Are you sure you want to permanently delete this record", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
                blnTrnasaction = True
                Call DeleteFromTable("tblItem", "ItemId=" & mlngRecordID)
                gtrnWebPlusMed.Commit()
                blnTrnasaction = False
                MessageBox.Show("Record deleted", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
                SendKeys.Send("{F5}")
            End If


        Catch ex As Exception
            If blnTrnasaction = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show("Record in use" & vbCrLf & "Cannot delete", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub
    Private Sub btnAddImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImageAdd.Click
        'Dim intUnload As DialogResult
        'strPath = "C:\"
        'If System.IO.Directory.Exists(strPath) = False Then
        '    System.IO.Directory.CreateDirectory(strPath)
        'End If
        'Dim sfdlg As New OpenFileDialog()
        'sfdlg.InitialDirectory = strPath
        'sfdlg.Filter = "Image Files (*.jpg;*.gif;*.bmp;*.ico;*.wmf;*.cur)|*.jpg;*.gif;*.bmp;*.ico;*.wmf;*.cur"
        'intUnload = sfdlg.ShowDialog()
        'If intUnload = Windows.Forms.DialogResult.OK Then
        '    strPath = sfdlg.FileName
        '    txtImagePath.Text = strPath
        '    Dim bm As New Bitmap(strPath)
        '    pcbImage.Image = bm
        '    pcbImage.Properties.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Stretch
        'End If

        Dim dlgFile As New OpenFileDialog

        dlgFile.Filter = "Image File(*.JPG)|*.JPG|Image File(*.BMP)|*.BMP|Image File (*.GIF)|*.GIF|All files (*.*)|*.*"


        If dlgFile.ShowDialog = DialogResult.Cancel Then
            Exit Sub
        Else
            'txtIFullPath.Text = dlgFile.FileName
            pcbImage.Tag = dlgFile.FileName
            pcbImage.Image = Nothing
            pcbImage.Image = Image.FromFile(dlgFile.FileName)
            pcbImage.Properties.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Stretch
        End If
    End Sub

    Private Sub btnRemoveImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImageRemove.Click
        pcbImage.Image = Nothing
        pcbImage.Tag = ""
    End Sub

    Private Sub txtPurchaseUnitCost_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPurchaseUnitCost.TextChanged
        mblnChanged = True
        If Val(txtDispensingUnit.Text) > 0 Then
            txtCostEach.Text = Math.Round(txtPurchaseUnitCost.EditValue / txtDispensingUnit.EditValue, 2)
        Else
            txtCostEach.EditValue = 0.0
        End If
    End Sub

    Private Sub txtDispensingUnit_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDispensingUnit.TextChanged
        mblnChanged = True
        If Val(txtPurchaseUnitCost.Text) > 0 Then
            txtCostEach.Text = Math.Round(txtPurchaseUnitCost.EditValue / txtDispensingUnit.EditValue, 2)
        Else
            txtCostEach.EditValue = 0.0
        End If
    End Sub

    Private Sub lkManufacturer_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkManufacturer.ButtonClick
        If e.Button.Index = 1 Then
            'Fill Manufacturer combo
            Call PopulateLookupDX(lkManufacturer, "ManufacturerName", "ManufacturerId", "vwManufacturerDetails", "ManufacturerId,ManufacturerName", , "ManufacturerName")
        End If
    End Sub

    Private Sub lkVendor_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkVendor.ButtonClick
        If e.Button.Index = 1 Then
            'Fill Vendor combo
            Call PopulateLookupDX(lkVendor, "VendorName", "VendorId", "vwVendorDetails", "VendorId,VendorName", , "VendorName")
        End If
    End Sub

    Private Sub lkPurchaseUnit_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkPurchaseUnit.ButtonClick
        If e.Button.Index = 1 Then
            'Fill Purchase Unit
            Call PopulateLookupDX(lkPurchaseUnit, "Units", "UnitId", "tblInventoryUnits", "UnitId,Units", , "Units")
        End If
    End Sub

    Private Sub lkDispensingUnit_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkDispensingUnit.ButtonClick
        If e.Button.Index = 1 Then
            'Fill Dispensing Unit
            Call PopulateLookupDX(lkDispensingUnit, "Units", "UnitId", "tblInventoryUnits", "UnitId,Units", , "Units")
        End If
    End Sub

    Private Sub txtItemCode_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _
    txtItemCode.TextChanged, txtShelfLife.TextChanged, txtReOrderQty.TextChanged, _
    txtReOrderPoint.TextChanged, txtQOH.TextChanged, txtPreferredQOH.TextChanged, txtItemName.TextChanged, _
    txtDetails.TextChanged, txtCharge.TextChanged, txtBarCodeNo.TextChanged, pcbImage.EditValueChanged, _
    lkVendor.EditValueChanged, lkPurchaseUnit.EditValueChanged, lkManufacturer.EditValueChanged, _
    lkDispensingUnit.EditValueChanged, lkCategory.EditValueChanged, txtOpeningStock.TextChanged
        mblnChanged = True
    End Sub

    Private Sub cboShelfPeriod_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboShelfPeriod.TextChanged
        mblnChanged = True
    End Sub

    Private Sub lkCategory_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles lkCategory.GotFocus, txtItemCode.GotFocus, txtShelfLife.GotFocus, txtReOrderQty.GotFocus, txtReOrderPoint.GotFocus, txtQOH.GotFocus, txtPreferredQOH.GotFocus, txtItemName.GotFocus, txtDetails.GotFocus, txtCharge.GotFocus, txtBarCodeNo.GotFocus, txtOpeningStock.GotFocus
        sender.SelectAll()
    End Sub

    Private Sub lkCategory_ButtonClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkCategory.ButtonClick
        If e.Button.Index = 1 Then
            'Fill Category combo
            Call PopulateLookupDX(lkCategory, "Category", "CategoryId", "tblCategory", "CategoryId,Category", "IsFixed=0", "Category")
        End If
    End Sub

    Private Sub lkCategory_ProcessNewValue(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs) Handles lkCategory.ProcessNewValue
        If IsDBNullOrNothing(e.DisplayValue) Then Exit Sub
        If MessageBox.Show("This value is not present in the list. Do you want to add it now?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            lkCategory.EditValue = Nothing
            lkCategory.Focus()
            Exit Sub
        End If
        With frmInventoryLookup
            .mblnFrmOutside = True
            .mstrItemName = e.DisplayValue
            .Tag = "Category"
            .ShowDialog()
            Call PopulateLookupDX(lkCategory, "Category", "CategoryId", "tblCategory", "CategoryId,Category", "IsFixed=0", "Category")
            If mlngLookUpId > 0 Then
                lkCategory.EditValue = CInt(mlngLookUpId)
            Else
                lkCategory.EditValue = Nothing
                lkCategory.Focus()
            End If
            .Dispose()
            GC.Collect()
        End With
        mlngLookUpId = Nothing
    End Sub

    Private Sub lkManufacturer_ProcessNewValue(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs) Handles lkManufacturer.ProcessNewValue
        If IsDBNullOrNothing(e.DisplayValue) Then Exit Sub
        If MessageBox.Show("This value is not present in the list. Do you want to add it now?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            lkManufacturer.EditValue = Nothing
            lkManufacturer.Focus()
            Exit Sub
        End If
        With frmManufacturer
            .mblnFrmOutside = True
            .mstrItemName = e.DisplayValue
            .ShowDialog()
            Call PopulateLookupDX(lkManufacturer, "ManufacturerName", "ManufacturerId", "vwManufacturerDetails", "ManufacturerId,ManufacturerName", , "ManufacturerName")
            If mlngLookUpId > 0 Then
                lkManufacturer.EditValue = CInt(mlngLookUpId)
            Else
                lkManufacturer.EditValue = Nothing
                lkManufacturer.Focus()
            End If
            .Dispose()
            GC.Collect()
        End With
        mlngLookUpId = Nothing
    End Sub

    Private Sub lkVendor_ProcessNewValue(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs) Handles lkVendor.ProcessNewValue
        If IsDBNullOrNothing(e.DisplayValue) Then Exit Sub
        If MessageBox.Show("This value is not present in the list. Do you want to add it now?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            lkVendor.EditValue = Nothing
            lkVendor.Focus()
            Exit Sub
        End If
        With frmVendor
            .mblnFrmOutside = True
            .mstrItemName = e.DisplayValue
            .ShowDialog()
            Call PopulateLookupDX(lkVendor, "VendorName", "VendorId", "vwVendorDetails", "VendorId,VendorName", , "VendorName")
            If mlngLookUpId > 0 Then
                lkVendor.EditValue = CInt(mlngLookUpId)
            Else
                lkVendor.EditValue = Nothing
                lkVendor.Focus()
            End If
            .Dispose()
            GC.Collect()
        End With
        mlngLookUpId = Nothing
    End Sub

    Private Sub lkPurchaseUnit_ProcessNewValue(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs) Handles lkPurchaseUnit.ProcessNewValue
        If IsDBNullOrNothing(e.DisplayValue) Then Exit Sub
        If MessageBox.Show("This value is not present in the list. Do you want to add it now?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            lkPurchaseUnit.EditValue = Nothing
            lkPurchaseUnit.Focus()
            Exit Sub
        End If
        With frmInventoryLookup
            .mblnFrmOutside = True
            .mstrItemName = e.DisplayValue
            .Tag = "Units"
            .ShowDialog()
            Call PopulateLookupDX(lkPurchaseUnit, "Units", "UnitId", "tblInventoryUnits", "UnitId,Units", , "Units")
            Call PopulateLookupDX(lkDispensingUnit, "Units", "UnitId", "tblInventoryUnits", "UnitId,Units", , "Units")
            If mlngLookUpId > 0 Then
                lkPurchaseUnit.EditValue = CInt(mlngLookUpId)
            Else
                lkPurchaseUnit.EditValue = Nothing
                lkPurchaseUnit.Focus()
            End If
            .Dispose()
            GC.Collect()
        End With
        mlngLookUpId = Nothing
    End Sub

    Private Sub lkDispensingUnit_ProcessNewValue(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs) Handles lkDispensingUnit.ProcessNewValue
        If IsDBNullOrNothing(e.DisplayValue) Then Exit Sub
        If MessageBox.Show("This value is not present in the list. Do you want to add it now?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            lkDispensingUnit.EditValue = Nothing
            lkDispensingUnit.Focus()
            Exit Sub
        End If
        With frmInventoryLookup
            .mblnFrmOutside = True
            .mstrItemName = e.DisplayValue
            .Tag = "Units"
            .ShowDialog()
            Call PopulateLookupDX(lkDispensingUnit, "Units", "UnitId", "tblInventoryUnits", "UnitId,Units", , "Units")
            Call PopulateLookupDX(lkPurchaseUnit, "Units", "UnitId", "tblInventoryUnits", "UnitId,Units", , "Units")
            If mlngLookUpId > 0 Then
                lkDispensingUnit.EditValue = CInt(mlngLookUpId)
            Else
                lkDispensingUnit.EditValue = Nothing
                lkDispensingUnit.Focus()
            End If
            .Dispose()
            GC.Collect()
        End With
        mlngLookUpId = Nothing
    End Sub

End Class
